// pages/scanCode.js
import {getElectronicInfoByCode, getProGoodsByCode, saveInstallRecord} from "../../api/sacnCode"
import {queryTree} from '../../api/sys'
import areaList from '../../utils/area'
import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'
let qqmapsdk
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showPicker: false,
        value: '',
        active: 0,
        isnone: false,
        steps: [
            {
                text: '扫电工码',
                inactiveIcon: '/images/inactiveIcon1.png',
                activeIcon: '/images/activeIcon1.png',
            },
            {
                text: '扫外机码',
                inactiveIcon: '/images/inactiveIcon2.png',
                activeIcon: '/images/activeIcon2.png',
            },
            {
                text: '扫内机码',
                inactiveIcon: '/images/inactiveIcon3.png',
                activeIcon: '/images/activeIcon3.png',
            },
            {
                text: '完善信息',
                inactiveIcon: '/images/inactiveIcon4.png',
                activeIcon: '/images/activeIcon4.png',
            },
        ],
        dataInfo: {},
        f: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
        showCarTypePicker: false,
        cartypeList: [], // 车型
        showYearPicker: false,
        cartYearList: ['2019年', '2020年'], // 年限
        showAddressPicker: false,
        areaList: [], //安装地点

    },
    toQueryTree(){
        queryTree({"code":"shipeichexing"}).then(res => {
            let {success, data} = res
            if (success) {
              const columns1 = data[0].children.map(item => {
                                    return {
                                        value: item.id,
                                        text: item.name,
                                        children: item.children
                                    }
                                })
              const columns2 = columns1[0].children.map(item => {
                                    return {
                                        value: item.id,
                                        text: item.name,
                                        children: item.children
                                    }
                                })
              const columns3 = columns2[0].children.map(item => {
                                    return {
                                        value: item.id,
                                        text: item.name,
                                        children: item.children
                                    }
                                })
                const cartypeList = [
                    {
                      values: columns1
                    },
                    {
                      values: columns2
                    },
                    {
                      values: columns3
                    }
                  ]
                this.setData({
                    cartypeList: cartypeList
                })
            }
        })
    },
    onChangeCarType(event) {
        const { picker, value, index } = event.detail;
        picker.setColumnValues(index + 1, value[index].children.map(item => {
            return {
                value: item.id,
                text: item.name,
                children: item.children
            }
        }))
        if (index === 0) {
            picker.setColumnValues(index + 2, value[index].children[0].children.map(item => {
                return {
                    value: item.id,
                    text: item.name,
                    children: item.children
                }
            }))
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        qqmapsdk = new QQMapWX({
          key: 'OCQBZ-3LW3J-7XLF5-KQB5A-GNJG6-7YB5K'
        })
        this.setData({
            'dataInfo.ownerName': app.globalData.userInfo.nickname,
            'dataInfo.ownerMobile': app.globalData.phone,
            areaList: areaList
        })
        // options.active = 3;
        if (options.active) {
            this.setData({
                active: options.active || 3,
            });
        }

        if (options.id) {
            wx.showLoading({
                title: '加载中',
            })
            if (options.active == "1" || options.active == "2") {
                let inOrOut = options.active == 1 ? 'OUT' : 'IN'
                //内外机
                getProGoodsByCode({sn: options.id || '', inOrOut: inOrOut}).then(result => {
                    wx.hideLoading()
                    if (result.success) {
                        this.setData({
                            dataInfo: result.data
                        });
                        let scanCodeInfo = wx.getStorageSync('scanCodeInfo') || {};
                        let codesn = {}
                        if (inOrOut == 'OUT') {
                            codesn = {outSn: result.data.sn}
                        } else {
                            codesn = {inSn: result.data.sn}
                        }
                        let data = Object.assign(scanCodeInfo, codesn)
                        wx.setStorageSync('scanCodeInfo', data)
                    }
                }).catch(err => {
                    wx.hideLoading()
                    this.setData({
                        isnone: true
                    })
                    let active = this.data.active
                    wx.showToast({
                      title: err.message || "扫描失败",
                      icon: 'none',
                      duration: 1500
                    })
                    setTimeout(function() {
                        wx.redirectTo({
                            url: '/pages/scanCode/scanCode?active=' + active,
                        });
                    }, 1500)
                })
            } else if (options.active == "0") {
                //电工
                getElectronicInfoByCode({id: options.id || ''}).then(result => {
                    wx.hideLoading()
                    if (result.success) {

                        this.setData({
                            dataInfo: result.data
                        });
                        let data = Object.assign(this.data.dataInfo, result.data)
                        wx.setStorageSync('scanCodeInfo', data)
                    }
                }).catch(err => {
                  wx.hideLoading()
                    this.setData({
                        isnone: true
                    })
                    wx.showToast({
                        title: err.message || "扫描失败",
                        icon: 'none',
                        duration: 1500
                    })
                    setTimeout(function() {
                        wx.redirectTo({
                            url: '/pages/scanCode/scanCode?active=0',
                        });
                    }, 1500)
                })
            } else {
              wx.hideLoading()
              this.getUserLocation()
              this.toQueryTree()
            }
        }
    },
    getUserLocation: function () {
      let vm = this;
      wx.getSetting({
        success: (res) => {
          console.log("getSetting");
          console.log(res)
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
          // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
          // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
            wx.showModal({
              title: '请求授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: function (res) {
                if (res.cancel) {
                  wx.showToast({
                    title: '拒绝授权',
                    icon: 'none',
                    duration: 1000
                  })
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function (dataAu) {
                      if (dataAu.authSetting["scope.userLocation"] == true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                        //再次授权，调用wx.getLocation的API
                        vm.getLocation();
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }
                  })
                }
              }
            })
          } else if (res.authSetting['scope.userLocation'] == undefined) {
            //调用wx.getLocation的API
            vm.getLocation();
          } else {
            //调用wx.getLocation的API
            vm.getLocation();
          }
        }
      })
    },
    // 微信获得经纬度
    getLocation: function () {
      let vm = this;
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          console.log("getLocation");
          console.log(res)
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy;
          vm.getLocal(latitude, longitude)
        },
        fail: function (res) {
          console.log('fail' + JSON.stringify(res))
        }
      })
    },
    // 获取当前地理位置
    getLocal: function (latitude, longitude) {
      let vm = this;
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: function (res) {
          console.log("getLocal");
          console.log(res);
          let province = res.result.ad_info.province
          let city = res.result.ad_info.city
          let district = res.result.ad_info.district
          
          const provinceCode = vm.findKey(areaList.province_list, province)
          const cityCode = vm.findKey(areaList.city_list, city)
          const districtCode = vm.findKey(areaList.county_list, district)

          let address = province + city + district
          const addressCode = `${provinceCode},${cityCode},${districtCode}`
          vm.setData({
              'dataInfo.installAddress': addressCode,
              'dataInfo.address': address
          });
        },
        fail: function (res) {
          console.log("fail");
          console.log(res);
        },
        complete: function (res) {
          // console.log(res);
        }
      });
    },
    findKey (data, value, compare = (a, b) => a === b) {
      return Object.keys(data).find(k => compare(data[k], value))
    },
    onChangeName(val) { // 姓名
        this.setData({
            dataInfo: Object.assign(this.data.dataInfo, {
                ownerName: val.detail
            })
        });
    },
    onChangeTel(val) { // 手机号
        this.setData({
            dataInfo: Object.assign(this.data.dataInfo, {
                ownerMobile: val.detail
            })
        });
    },
    validCodeChange(val) { // 验证码
        this.setData({
            dataInfo: Object.assign(this.data.dataInfo, {
                validCode: val.detail
            })
        });
    },
    onCarLicense(val) { // 车牌号
        this.setData({
            dataInfo: Object.assign(this.data.dataInfo, {
                carLicense: val.detail
            })
        });
    },
    onChange(event) {
        // event.detail 为当前输入的值
        console.log(event.detail);
    },
    showPopup() {
        this.setData({showPicker: true});
    },
    onClose() {
        this.setData({showPicker: false});
    },
    //选择车型
    showCarType() {
        this.setData({showCarTypePicker: true});
    },
    onCloseCarType() {
        this.setData({showCarTypePicker: false});
    },
    onConfirmCarType(event) { //选择车型
        const {value} = event.detail;
        const carTypeValue = value.filter(item => !!item)
        this.setData({
            'dataInfo.carType': carTypeValue[carTypeValue.length - 1].value,
            'dataInfo.carTypeLabel': carTypeValue[carTypeValue.length - 1].text,
            showCarTypePicker: false
        })
    },
    onCancelCarType() {
        this.setData({showCarTypePicker: false});
    },

    //年限
    showPopupYearLimit() {
        this.setData({showYearPicker: true});
    },
    onCloseYearLimit() {
        this.setData({showYearPicker: false});
    },
    onConfirmYearLimit(event) {
        const {picker, value, index} = event.detail;
        this.setData({
            dataInfo: Object.assign(this.data.dataInfo, {
                carYearLimit: value
            }),
            showYearPicker: false
        });
    },
    onCancelYearLimit() {
        this.setData({showYearPicker: false});
    },

    //安装地点
    showPopupAddress() {
        this.setData({showAddressPicker: true});
    },
    onCloseAddress() {
        this.setData({showAddressPicker: false});
    },
    onConfirmAddress(event) {
        const {values} = event.detail;
        let address = values[0].name + values[1].name + values[2].name
        const addressCode = `${values[0].code},${values[1].code},${values[2].code}`
        this.setData({
            dataInfo: Object.assign(this.data.dataInfo, {
                installAddress: addressCode,
                address: address
            }),
            showAddressPicker: false
        });
    },
    onCancelAddress() {
        this.setData({showAddressPicker: false});
    },
    /**
     * 图片上传
     */
    afterRead(event) {
      let _this = this
      wx.showLoading({
          title: '加载中',
      })
      const {file} = event.detail;
      wx.uploadFile({
          url: `${app.globalData.baseUrl}/sys/attachment/upload`,
          filePath: file.url,
          name: 'file',
          success(res) {
              let {data, success} = JSON.parse(res.data)
              if (success) {
                  _this.setData({
                      'dataInfo.logisticsImg': data.attachment
                  })
              }
              wx.hideLoading()
          }
      });
  },
  deleteImg(e) {
      this.setData({
          'dataInfo.logisticsImg': ''
      })
  },
    handleNext() {
        this.data.active = Number(this.data.active) + 1;
        if (this.data.active < "3") {
            wx.redirectTo({
                url: '/pages/scanCode/scanCode?active=' + this.data.active,
            });
        } else if (this.data.active > '2') { //完善信息
            wx.redirectTo({
                url: '/pages/scanCodeOld/scanCodeOld?active=' + this.data.active,
            })

        }

    },
    handleAddCard() { // 生成质保卡
        let scanCodeInfo = wx.getStorageSync('scanCodeInfo');
        let params = Object.assign(scanCodeInfo, this.data.dataInfo, {ownerId: app.globalData.userId})
        saveInstallRecord(params).then(result => {
            if (result.success) {
                // 生成后传递新创建的评价ID：evaluateId
                wx.redirectTo({
                    url: `/pages/createCard/createCard?evaluateId=${result.data.evaluateId}`
                })
            }


        }).catch(err => {
            this.setData({
                isnone: true
            })
            let active = this.data.active
            setTimeout(function () {
                wx.redirectTo({
                    url: '/pages/scanCode/scanCode?active=' + active,
                });
            }, 2000)
            console.log(err)
        })
    },
    condition(num) {
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
